import Vue from 'vue'
import Router from 'vue-router'
import Env from './env'
import { plain } from './menu'

Vue.use(Router)

function lazyLoadedComponent(path) {
  // return resolve => require(['@/components' + path], resolve)
  return resolve => require.ensure([], () => resolve(require('@/' + path)))
}

/**
 * build component from plain json object
 * auto generate meta properties include module/menu/breadcrums
 * @param {Component} node
 */
function buildComponent(node) {
  var components = []
  let currentBreadcrums = node.meta.breadcrums || [
    { label: node.label, to: { path: node.path } }
  ]
  node.children && node.children.forEach(function (child) {
    const breadcrums = currentBreadcrums.slice()
    breadcrums.push({ label: child.label, to: { path: child.path } })

    let component = Object.assign({}, child)
    component.meta = Object.assign({
      module: node.meta.module,
      menu: node.meta.menu || component.path,
      breadcrums: breadcrums,
      title: child.label
    }, component.meta)
    component.component = lazyLoadedComponent(component.component)
    components.push(component)

    const children = buildComponent(component)
    components = components.concat(children)
  }, this)

  delete node.children
  return components
}

let router = new Router({
  mode: Env.routerMode,
  strict: !Env.isProd,
  routes: [{
    path: '/login',
    name: 'login',
    component: lazyLoadedComponent('views/member/Login.vue'),
    meta: {
      anon: true
    }
  }, {
    path: '/register',
    name: 'register',
    component: lazyLoadedComponent('views/member/register.vue'),
    meta: {
      anon: true
    }
  }, {
    alias: '/',
    path: '/dashboard', // dashboard home
    name: 'dashboard',
    component: lazyLoadedComponent('components/dashboard.vue'),
    children: (() => {
      let components = []
      for (const key in plain) {
        if (!plain.hasOwnProperty(key)) continue
        let node = Object.assign({ meta: { module: key } }, plain[key])
        const result = buildComponent(node)
        components = components.concat(result)
      }
      return components
    })()
  }]
})

// authentication checking before enter each page
router.beforeEach((to, from, next) => {
  document.title = ((to.meta && to.meta.title) || '欢迎您') + ' - 管理后台'
  // only router with meta.anon equal true does not need authentication checking
  if (!(to.meta && to.meta.anon)) {
    const profile = localStorage.getObject('profile')
    profile && profile.token || next({ path: '/login', query: { success: to.fullPath } })
  }
  next()
})

export default router
